#include "databaseoverviewwidget.h"
#include <QHeaderView>
#include <QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>

QString DatabaseOverviewWidget::property_names[NUMBER_OF_DATABASE_PROPERITIES]={
    tr("db"),tr("collections"),tr("objects"),tr("avgObjSize"),
    tr("dataSize"),tr("storageSize"),tr("numExtent"),
    tr("indexes"),tr("indexeSize"),tr("fileSize"),tr("ok")

};
DatabaseOverviewWidget::DatabaseOverviewWidget(BSONObj& bsonObj,QWidget* parent) :
    QDialog(parent)
{
    cout<<bsonObj.toString()<<endl;
    okButton=new QPushButton(tr("OK"));
    cancelButton=new QPushButton(tr("Cancel"));

    treeWidget=new QTreeWidget;
    treeWidget->setColumnCount(2);
    treeWidget->setHeaderLabels(
                QStringList()<<tr("Property")<<tr("Value")
                );
    treeWidget->header()->setResizeMode(0,QHeaderView::Stretch);
    treeWidget->header()->setResizeMode(1,QHeaderView::Stretch);
    addChildBsonObjs(bsonObj,0);
    treeWidget->sortByColumn(0);
    treeWidget->setFocus();
    QHBoxLayout* hLayout=new QHBoxLayout;
    QVBoxLayout* vLayout=new QVBoxLayout;
    vLayout->addWidget(okButton);
    vLayout->addWidget(cancelButton);
    hLayout->addWidget(treeWidget);
    hLayout->addLayout(vLayout);
    setLayout(hLayout);

   // treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
}

void DatabaseOverviewWidget::addChildBsonObjs(BSONObj bsonObj, QTreeWidgetItem *parent)
{
    if (!parent)
        parent = treeWidget->invisibleRootItem();
    QTreeWidgetItem *item;
    vector<BSONElement> subBsonElems;
    bsonObj.elems(subBsonElems);
    for(int i=0;i<subBsonElems.size();i++)
    {
        item=new QTreeWidgetItem(parent);
        item->setText(0,QString::fromStdString(subBsonElems[i].fieldName()));
        if(subBsonElems[i].type()==mongo::Object)
        {
            addChildBsonObjs(subBsonElems[i].Obj(),item);
        }
        else
        {
            //对类型进行判断，以正确的显示
            string elemStr=subBsonElems[i].toString();
            string value=elemStr.erase(0,elemStr.find(':',0));
            item->setText(1,tr("%1").arg(value.c_str()));
        }
    }
}

//void DatabaseOverviewWidget::contextMenuEvent(QContextMenuEvent *event)
//{
//    //QPoint pos;
//    QTreeWidgetItem *item = NULL;
//    QPoint point = event->pos();//等到窗口坐标
//    item = treeWidget->itemAt(point);//这里不管是不是点击item上都为默认选中item
//    if(item != NULL)
//    {
//        QMenu *menu = new QMenu();
//        menu->addSeparator();
//        menu->addSeparator();
//        menu->exec(event->globalPos());
//        delete menu;
//    }
//    event->accept();
//}

